<template>
  <div class="xn-upload-files">
    <upload-file-base
      :file-list="fileList"
      :upload-title="uploadTitle"
      :max-limit="maxLimit"
      :accept="accept"
      :img-cropper-config="imgCropperConfig"
      :http-request="uploadFiles"
      :disabled="disabled"
      :layout="layout"
      :accept-inline="acceptInline"
      @change="onFileChange"></upload-file-base>
    <div class="uploaded-files" v-if="fileList.length">
      <div class="box-title">
        <i class="el-icon-paperclip"></i>
        已上传附件（{{ fileList.length }}个）
      </div>
      <upload-preview
        class="preview-list"
        :fileList="fileList"
        :layout="layout"
        :show-delete="!disabled"
        @fileRemove="$emit('change')"></upload-preview>
    </div>
  </div>
</template>

<script>
import { uploadFiles } from '@api/api.js'
import UploadFileBase from './UploadFileBase.vue'
import UploadPreview from './UploadPreview/index.vue'
export default {
  name: 'XnUploadFiles',
  components: { UploadFileBase, UploadPreview },
  props: {
    fileList: {
      type: Array,
      default: () => [],
    },
    // 标题
    uploadTitle: {
      type: String,
      default: '上传附件',
    },
    // 数量限制
    maxLimit: {
      type: Number,
      default: 9,
    },
    accept: {
      type: String,
      default: '.pdf,.ofd,.doc,.docx,.xls,.xlsx,.wps,.jpeg,.png,.jpg',
    },
    // TODO 图片上传模式暂时只支持单张上传
    imgCropperConfig: {
      type: Object,
      default: () => ({
        enableCropper: false,
        width: 600,
        height: 400,
      }),
    },
    disabled: {
      type: Boolean,
    },
    layout: {
      type: String,
      default: 'list',
    },
    acceptInline: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {}
  },
  methods: {
    uploadFiles(formData, onSuccess, onFailed, onProgress) {
      uploadFiles(formData, onProgress)
        .then(res => {
          console.log('httpRequest...', res)
          if (res.status === 200) {
            onSuccess && onSuccess(res)
            return
          }
          onFailed && onFailed()
        })
        .catch(() => {
          onFailed && onFailed()
        })
    },
    onFileChange() {
      this.$emit('change')
    },
  },
}
</script>

<style lang="scss" scoped>
.xn-upload-files {
  .uploaded-files {
    margin-top: 10px;
    border: 1px solid #dddddd;
    .box-title {
      padding: 0 10px;
      background-color: #efefef;
      font-size: 14px;
      color: #333333;
      .el-icon-paperclip {
        color: #666;
        margin-right: 5px;
      }
    }
    .preview-list {
      padding: 10px;
    }
  }
}
</style>
